<?php

namespace App\Api\Controllers;

use App\Api\Requests\ClerkRequest;
use App\Api\TransFormers\ClerkTransformer;
use App\Models\WriteOffs;
use App\Models\User;
use Carbon\Carbon;
use PhpParser\Node\Scalar\String_;

class ClerkController extends BaseController
{
    /**
     * 核销员列表
     * @param ClerkRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function list(ClerkRequest $request){
        $userInfo = User::where('openid',$request->get('openid'))->select('id')->first();
        $info = WriteOffs::with('user')->where('user_id',$userInfo->id)->get();
        return $this->response->collection($info,new ClerkTransformer());
    }

    /**
     * 删除核销员
     * @param ClerkRequest $request
     * @return \Dingo\Api\Http\Response|void
     */
    public function delete(ClerkRequest $request){
        $info = WriteOffs::findOrFail($request->get('id'));
        if($info->delete()){
            return $this->response->created();
        }else{
            return $this->response->errorInternal();
        }

    }

    /**
     * 添加核销员二维码
     */
    public function code(ClerkRequest $request)
    {
        //获取用户openid
        $openid = $request->get('openid');
        $url = $this->getqrcode($openid);
        if($url){
            $data = ['data'=>$url];
            return $data;
        }
        return $this->response->errorInternal();
    }

    /**绑定核销员
     * @return mixed|string
     */
    public function bind(ClerkRequest $request){
        //获取店长和店员的openid
        $info = User::where('openid',$request->get('id'))->first();
        $cinfo = User::where('openid',$request->get('cid'))->first();
        $data['user_id'] = $info->id;
        $data['write_offs_id'] = $cinfo->id;
        if($data['user_id'] == $data['write_offs_id']){
            $re['data']['content'] = '您是发布人,无需绑定';
            $re['data']['type'] = 1;
            return $re;
        }
        $where = [];
        array_push($where,['user_id',$data['user_id']]);
        array_push($where,['write_offs_id',$data['write_offs_id']]);
        $res = WriteOffs::where($where)->first();
        if($res){
            $re['data']['content'] = '已绑定，无需再次绑定';
            $re['data']['type'] = 2;
            return $re;
        }
        $data['created_at'] = Carbon::now();
        WriteOffs::insert($data);
        return $this->response->created();
    }
}
